from llvmlite import ir
from pycparser import c_ast as ast
from pycparser import c_ast, parse_file


class LLVMGenerator:
    def __init__(self):
        self.module = ir.Module("my_module")
        self.builder = None
        self.symbol_table = {}
        self.globals = {}
        self.functions = {}
        self.current_function = None
        self.loop_stack = []
        self.struct_types = {}  # {name: (ir_type, layout_info)}
        self.enum_values = {}  # 存储枚举常量值

    def generate(self, node):
        self.visit(node)
        return self.module

    def visit(self, node, **kwargs):
        method = "visit_" + node.__class__.__name__
        return getattr(self, method, self.generic_visit)(node, **kwargs)

    def generic_visit(self, node, as_ptr=False):
        raise RuntimeError(f"Unhandled node type: {node.__class__.__name__}")

    def visit_While(self, node):
        # 创建循环基本块
        func = self.current_function
        cond_block = func.append_basic_block("while.cond")
        body_block = func.append_basic_block("while.body")
        end_block = func.append_basic_block("while.end")

        # 压入循环上下文栈
        self.loop_stack.append((cond_block, end_block))

        # 生成初始跳转
        self.builder.branch(cond_block)

        # 处理条件判断
        self.builder.position_at_end(cond_block)
        cond_value = self.visit(node.cond)
        self.builder.cbranch(cond_value, body_block, end_block)

        # 处理循环体
        self.builder.position_at_end(body_block)
        self.visit(node.stmt)
        # 自动添加回到条件判断的跳转
        if not self.block_terminated(body_block):
            self.builder.branch(cond_block)

        # 结束位置
        self.builder.position_at_end(end_block)
        # 弹出循环上下文
        self.loop_stack.pop()

    def visit_Continue(self, node):
        if not self.loop_stack:
            raise RuntimeError("continue statement not within loop")

        # 获取最近的循环条件块
        cond_block, _ = self.loop_stack[-1]
        # 生成无条件跳转
        self.builder.branch(cond_block)
        # 标记当前块已终止
        self.terminate_current_block()

    def visit_Break(self, node):
        if not self.loop_stack:
            raise RuntimeError("break statement not within loop")

        # 获取最近的循环结束块
        _, end_block = self.loop_stack[-1]
        # 生成无条件跳转
        self.builder.branch(end_block)
        # 标记当前块已终止
        self.terminate_current_block()

    # 辅助方法
    def block_terminated(self, block):
        """检查基本块是否已有终止指令"""
        return block.instructions and isinstance(block.instructions[-1], ir.Terminator)

    def terminate_current_block(self):
        """标记当前块为已终止"""
        current_block = self.builder.block
        if not self.block_terminated(current_block):
            # 添加不可达指令作为占位
            self.builder.unreachable()

    # 关键修改点1：处理文件AST
    def visit_FileAST(self, node):
        for ext in node.ext:
            self.visit(ext)

    # 关键修改点2：处理函数定义
    def visit_FuncDef(self, node):
        func_type = self.get_type(node.decl.type)
        func_name = node.decl.name
        params = self.get_params(node.decl.type)
        func = ir.Function(self.module, func_type, name=func_name)
        self.functions[func_name] = func
        self.current_function = func

        entry_block = func.append_basic_block("entry")
        self.builder = ir.IRBuilder(entry_block)

        # 处理参数
        for i, param in enumerate(func.args):
            param_name = node.decl.type.args.params[i].name
            alloca = self.builder.alloca(param.type, name=param_name)
            self.builder.store(param, alloca)
            self.symbol_table[param_name] = alloca

        # 处理函数体
        self.visit(node.body)

        # 添加默认返回（如果函数没有返回语句）
        if func_type.return_type == ir.VoidType():
            self.builder.ret_void()

    # 关键修改点3：处理复合语句
    def visit_Compound(self, node):
        if node.block_items is not None:
            for item in node.block_items:
                self.visit(item)

    def visit_PtrDecl(self, node):
        """处理指针类型声明"""
        # 递归解析指针指向的类型
        pointee_type = self.visit(node.type)
        return ir.PointerType(pointee_type)

    def visit_TypeDecl(self, node):
        """处理类型声明（返回结构体实际类型）"""
        # 递归解析底层类型
        base_type = self.visit(node.type)

        # 处理结构体类型引用
        if isinstance(node.type, ast.Struct):
            struct_name = node.type.name
            if struct_name not in self.struct_types:
                raise RuntimeError(f"未定义的结构体类型: {struct_name}")
            return self.struct_types[struct_name][0]  # 返回结构体类型本身

        return base_type

    def visit_IdentifierType(self, node):
        type_map = {
            "int": ir.IntType(32),
            "float": ir.FloatType(),
            "char": ir.IntType(8),
            "void": ir.VoidType(),
        }
        return type_map[node.names[0]]

    def visit_ArrayDecl(self, node):
        elem_type = self.visit(node.type)  # 解析元素类型（如i32）
        # 获取维度并强制转为整数
        size = self.visit(node.dim) if node.dim else 0
        if isinstance(size, ir.Constant):  # 防御性处理
            size = size.constant
        return ir.ArrayType(elem_type, size)  # 确保size是int

    def visit_ArrayRef(self, node, as_ptr=False):
        """处理多维数组访问（逐层生成GEP指令）"""
        # 递归解析基地址（可能是嵌套的ArrayRef）
        base_ptr = self.visit(node.name, as_ptr=True)

        # 获取当前层级的索引值
        current_idx = self.visit(node.subscript)

        # 统一构建GEP索引：[结构体索引0, 当前维度索引]
        gep_indices = [
            self.get_const_int(0),  # 数组到指针转换的隐式索引
            current_idx,  # 当前维度的显式索引
        ]

        # 生成当前层级的GEP指令
        elem_ptr = self.builder.gep(base_ptr, gep_indices, inbounds=True)

        return elem_ptr if as_ptr else self.builder.load(elem_ptr)

    def get_array_dims(self, node):
        """获取维度时保持声明顺序（外层→内层）"""
        dims = []
        while isinstance(node, ast.ArrayDecl):
            dim = self.eval_constant(node.dim) if node.dim else 0
            dims.append(dim)
            node = node.type
        return dims  # 示例：int a[10][2] → [10, 2]

    def get_const_int(self, value):
        return ir.Constant(ir.IntType(32), value)

    def normalize_init(self, init_node, current_depth, dims):
        """递归标准化初始化列表结构"""
        if current_depth >= len(dims):
            return init_node  # 到达最内层

        if isinstance(init_node, ast.InitList):
            # 处理显式初始化列表
            children = []
            for expr in init_node.exprs:
                normalized = self.normalize_init(expr, current_depth + 1, dims)
                children.append(normalized)
            # 填充剩余维度
            for _ in range(len(children), dims[current_depth]):
                default = ast.Constant(type="int", value="0")
                children.append(self.normalize_init(default, current_depth + 1, dims))
            return children
        else:
            # 标量值扩展为嵌套结构
            return [
                self.normalize_init(init_node, current_depth + 1, dims)
                for _ in range(dims[current_depth])
            ]

    def is_zero_initializer(self, init_node):
        """判断是否全零初始化"""
        if isinstance(init_node, ast.InitList):
            return all(self.is_zero_initializer(e) for e in init_node.exprs)
        return isinstance(init_node, ast.Constant) and int(init_node.value) == 0

    def init_array(self, arr_ptr, dims, init_values, depth=0):
        """优化后的数组初始化"""
        if depth == len(dims):
            return

        current_dim = dims[depth]
        for idx in range(current_dim):
            elem_ptr = self.builder.gep(
                arr_ptr, [self.get_const_int(0), self.get_const_int(idx)], inbounds=True
            )

            if depth == len(dims) - 1:
                # 最内层初始化
                if idx < len(init_values):
                    value = self.visit(init_values[idx])
                    self.builder.store(value, elem_ptr)
            else:
                # 递归处理子数组
                sub_init = init_values[idx] if idx < len(init_values) else []
                self.init_array(elem_ptr, dims, sub_init, depth + 1)

    # 关键修改点4：处理变量声明
    def visit_Decl(self, node):
        # 处理类型声明（Struct/Union/Enum）
        if isinstance(node.type, (ast.Struct, ast.Union, ast.Enum)):
            self.visit(node.type)
            return

        # 处理变量类型
        var_type = self.visit(node.type)
        if var_type is None:
            coord = node.coord if hasattr(node, "coord") else ""
            raise RuntimeError(f"类型解析失败: {node.name} {coord}")
        if self.current_function:
            # 局部数组变量的处理
            if isinstance(node.type, ast.ArrayDecl):
                array_type = self.visit(node.type)
                alloca = self.builder.alloca(array_type, name=node.name)
                self.symbol_table[node.name] = alloca

                if node.init:
                    # 检查是否全零初始化
                    if self.is_zero_initializer(node.init):
                        # 使用memset优化
                        self.builder.store(ir.Constant(array_type, None), alloca)
                    else:
                        # 部分初始化处理
                        dims = self.get_array_dims(node.type)
                        normalized = self.normalize_init(node.init, 0, dims)
                        self.init_array(alloca, dims, normalized)
            else:
                # 普通局部变量的处理
                if isinstance(var_type, ir.VoidType):
                    raise TypeError("不能声明void类型的变量")

                alloca = self.builder.alloca(var_type, name=node.name)
                self.symbol_table[node.name] = alloca
                if node.init:
                    init_value = self.visit(node.init)
                    if isinstance(var_type, ir.PointerType):
                        # 指针类型的初始化需要存储地址
                        self.builder.store(init_value, alloca)
                    else:
                        # 普通类型直接存储值
                        self.builder.store(init_value, alloca)
        else:
            # 全局数组的处理（需常量初始化）
            gvar = ir.GlobalVariable(self.module, var_type, name=node.name)
            if node.init:
                if isinstance(node.init, ast.InitList):
                    # 初始化全局数组（例如 [i32 0, i32 0, ...]）
                    const_array = ir.Constant(
                        var_type, [self.visit(expr) for expr in node.init.exprs]
                    )
                    gvar.initializer = const_array
                else:
                    gvar.initializer = self.visit(node.init)
            else:
                gvar.initializer = ir.Constant(var_type, None)
            self.globals[node.name] = gvar

    # 关键修改点5：处理循环结构
    def visit_While(self, node):
        loop_cond = self.current_function.append_basic_block("loop.cond")
        loop_body = self.current_function.append_basic_block("loop.body")
        loop_end = self.current_function.append_basic_block("loop.end")

        self.loop_stack.append((loop_cond, loop_end))
        self.builder.branch(loop_cond)

        # 处理条件
        self.builder.position_at_end(loop_cond)
        cond = self.visit(node.cond)
        self.builder.cbranch(cond, loop_body, loop_end)

        # 处理循环体
        self.builder.position_at_end(loop_body)
        self.visit(node.stmt)
        self.builder.branch(loop_cond)

        self.builder.position_at_end(loop_end)
        self.loop_stack.pop()

    def visit_If(self, node):
        # 生成条件表达式
        cond = self.visit(node.cond)

        # 创建基本块
        then_block = self.builder.append_basic_block("if.then")
        else_block = (
            self.builder.append_basic_block("if.else") if node.iffalse else None
        )
        merge_block = self.builder.append_basic_block("if.end")

        # 根据条件跳转
        if else_block:
            self.builder.cbranch(cond, then_block, else_block)
        else:
            self.builder.cbranch(cond, then_block, merge_block)

        # 生成then块
        self.builder.position_at_end(then_block)
        self.visit(node.iftrue)
        # 跳转到合并块
        if not self.block_terminated(then_block):
            self.builder.branch(merge_block)

        # 生成else块（如果有）
        if else_block:
            self.builder.position_at_end(else_block)
            self.visit(node.iffalse)
            if not self.block_terminated(else_block):
                self.builder.branch(merge_block)

        # 移动到合并块
        self.builder.position_at_end(merge_block)

        # 创建新块用于后续代码，并跳转过去
        cont_block = self.builder.append_basic_block("if.cont")
        self.builder.branch(cont_block)
        self.builder.position_at_end(cont_block)

    def block_terminated(self, block):
        """精确判断基本块是否已终止"""
        if block.is_terminated:
            return True
        if block.instructions:
            last_instr = block.instructions[-1]
            return isinstance(last_instr, (ir.Ret, ir.Branch, ir.Unreachable))
        return False

    # 关键修改点7：处理函数调用
    def visit_FuncCall(self, node):
        func_name = node.name.name
        args = [self.visit(arg) for arg in node.args.exprs] if node.args else []

        if func_name == "printf":
            fmt_str = args[0]
            args = [fmt_str] + args[1:]
            func_type = ir.FunctionType(
                ir.IntType(32), [ir.PointerType(ir.IntType(8))], var_arg=True
            )
            func = self.module.declare_function(func_name, func_type)
        else:
            func = self.functions[func_name]
        return self.builder.call(func, args)

    # 关键修改点8：处理二元操作
    def visit_BinaryOp(self, node):
        lhs = self.visit(node.left)
        rhs = self.visit(node.right)

        # 空值检查
        if lhs is None or rhs is None:
            raise RuntimeError(f"操作数缺失于 {node.coord}")

        # 强制类型统一
        if lhs.type != rhs.type:
            rhs = self.cast_value(rhs, lhs.type)

        # 验证操作数类型有效性
        valid_types = (ir.IntType, ir.FloatType, ir.PointerType)
        if not isinstance(lhs.type, valid_types):
            raise TypeError(f"不支持的比较类型: {lhs.type}")

        # 生成比较指令
        if node.op == ">":
            return self.builder.icmp_signed(">", lhs, rhs)
        if node.op == "<":
            return self.builder.icmp_signed("<", lhs, rhs)
        elif node.op == "+":
            return self.builder.add(lhs, rhs)
        elif node.op == "-":
            return self.builder.sub(lhs, rhs)
        elif node.op == "==":
            return self.builder.icmp_signed("==", lhs, rhs)

    # 其他辅助方法
    def get_type(self, type_node):
        """递归解析类型声明"""
        if isinstance(type_node, ast.Struct):
            # 如果结构体尚未定义，立即处理声明
            if type_node.name not in self.struct_types:
                self.visit_Struct(type_node)
            return self.struct_types[type_node.name][0]
        elif isinstance(type_node, ast.ArrayDecl):
            elem_type = self.get_type(type_node.type)
            dim = self.eval_constant(type_node.dim)
            return ir.ArrayType(elem_type, dim)
        elif isinstance(type_node, ast.PtrDecl):
            return ir.PointerType(self.get_type(type_node.type))

        elif isinstance(type_node, ast.TypeDecl):
            return self.get_type(type_node.type)

        elif isinstance(type_node, ast.IdentifierType):
            type_name = " ".join(type_node.names)
            if type_name == "int":
                return ir.IntType(32)
            elif type_name == "void":
                return ir.VoidType()
            elif type_name == "char":
                return ir.IntType(8)
            else:
                # 处理自定义类型（如结构体）
                return ir.IntType(32)  # 默认处理为int

        elif isinstance(type_node, ast.ArrayDecl):
            element_type = self.get_type(type_node.type)
            dim = self.eval_constant(type_node.dim) if type_node.dim else 0
            return ir.ArrayType(element_type, dim)

        elif isinstance(type_node, ast.PtrDecl):
            pointee_type = self.get_type(type_node.type)
            return ir.PointerType(pointee_type)

        elif isinstance(type_node, ast.FuncDecl):
            return_type = self.get_type(type_node.type)

            # 解析参数类型
            arg_types = []
            if type_node.args:
                for param in type_node.args.params:
                    param_type = self.get_type(param.type)
                    arg_types.append(param_type)

            return ir.FunctionType(return_type, arg_types)

        else:
            raise NotImplementedError(f"Unsupported type: {type(type_node)}")

    def eval_constant(self, expr):
        """计算常量表达式（用于数组维度）"""
        if isinstance(expr, ast.Constant):
            return int(expr.value)
        elif isinstance(expr, ast.UnaryOp):
            if expr.op == "-":
                return -self.eval_constant(expr.expr)
            elif expr.op == "+":
                return self.eval_constant(expr.expr)
        elif isinstance(expr, ast.BinaryOp):
            left = self.eval_constant(expr.left)
            right = self.eval_constant(expr.right)
            if expr.op == "+":
                return left + right
            if expr.op == "-":
                return left - right
            if expr.op == "*":
                return left * right
            if expr.op == "/":
                return left // right
        raise ValueError(f"Unsupported constant expression: {expr}")

    def get_params(self, type_node):
        params = []
        if isinstance(type_node, ast.FuncDecl):
            if type_node.args:
                for param in type_node.args.params:
                    param_type = self.get_type(param.type)
                    params.append(param_type)
        return params

    def visit_Constant(self, node):
        # 返回 LLVM 常量而非 Python 原生类型
        if node.type == "int":
            return ir.Constant(ir.IntType(32), int(node.value))
        elif node.type == "float":
            return ir.Constant(ir.FloatType(), float(node.value))
        else:
            raise ValueError(f"Unsupported constant type: {node.type}")

    def visit_ID(self, node, as_ptr=False):
        if node.name in self.symbol_table:
            ptr = self.symbol_table[node.name]
            return ptr if as_ptr else self.builder.load(ptr)
        elif node.name in self.globals:
            return self.globals[node.name]
        else:
            raise RuntimeError(f"Undefined variable: {node.name}")

    def visit_Assignment(self, node):
        # 处理左值类型
        if isinstance(node.lvalue, ast.UnaryOp) and node.lvalue.op == "*":
            # 处理解引用 *p = ...
            ptr_ptr = self.visit(node.lvalue.expr, as_ptr=True)
            ptr = self.builder.load(ptr_ptr)
            target_ptr = ptr
        elif isinstance(node.lvalue, (ast.ArrayRef, ast.StructRef, ast.ID)):
            # 直接获取数组元素/结构体成员/变量的地址
            target_ptr = self.visit(node.lvalue, as_ptr=True)
        else:
            raise NotImplementedError(f"Unsupported lvalue: {type(node.lvalue)}")

        # 处理右值
        value = self.visit(node.rvalue)

        # 类型兼容检查（添加指针验证）
        if not isinstance(target_ptr.type, ir.PointerType):
            raise TypeError(f"Left value must be a pointer type, got {target_ptr.type}")
        target_type = target_ptr.type.pointee

        # 类型转换（如果需要）
        if value.type != target_type:
            value = self.cast_value(value, target_type)

        # 生成存储指令
        self.builder.store(value, target_ptr)

    def visit_Return(self, node):
        # 确保当前块未终止
        if self.block_terminated(self.builder.block):
            return

        # 生成返回值
        if node.expr:
            value = self.visit(node.expr)
            self.builder.ret(value)
        else:
            self.builder.ret_void()

    def visit_Struct(self, node):
        """处理结构体定义（增强类型注册可靠性）"""
        struct_name = node.name

        # 确保结构体类型预注册
        if struct_name not in self.struct_types:
            context = self.module.context
            ir_type = context.get_identified_type(struct_name)
            self.struct_types[struct_name] = (ir_type, None)

        # 如果已完整定义则跳过
        if self.struct_types[struct_name][1] is not None:
            return

        # 深度优先处理成员类型
        for decl in node.decls:
            current_type = decl.type
            # 递归解析嵌套类型声明
            while isinstance(current_type, (ast.TypeDecl, ast.PtrDecl)):
                current_type = current_type.type
            if isinstance(current_type, ast.Struct):
                self.visit(current_type)  # 确保先处理嵌套结构体

        # 开始布局计算
        members = []
        member_info = []
        current_offset = 0

        for decl in node.decls:
            # 获取成员类型
            member_type = self.get_type(decl.type)
            member_name = decl.name

            # 计算对齐
            align = self.get_alignment(member_type)
            if align is None:
                raise RuntimeError(f"成员 {member_name} 的对齐值未知")

            # 计算填充
            padding = (align - (current_offset % align)) % align
            current_offset += padding

            # 记录成员信息
            members.append(member_type)
            member_info.append((member_name, member_type, current_offset))
            current_offset += self.get_size(member_type)

        # 结构体最终对齐
        max_align = max((self.get_alignment(t) for t in members), default=1)
        total_size = current_offset + (-current_offset % max_align)

        # 更新结构体信息
        ir_type.set_body(*members)
        self.struct_types[struct_name] = (
            self.struct_types[struct_name][0],
            {"size": total_size, "align": max_align, "members": member_info},
        )

    def visit_UnaryOp(self, node, as_ptr=False):
        """处理一元操作符（&和*）"""
        if node.op == "&":
            # 取地址操作
            target = self.visit(node.expr, as_ptr=True)
            return target
        elif node.op == "*":
            # 解引用操作
            ptr = self.visit(node.expr)
            if not isinstance(ptr.type, ir.PointerType):
                raise TypeError("解引用操作需要指针类型")
            return self.builder.load(ptr) if not as_ptr else ptr
        else:
            raise NotImplementedError(f"不支持的一元操作符: {node.op}")

    def visit_StructRef(self, node, as_ptr=False):
        """处理结构体成员访问（精确类型验证）"""
        base_ptr = self.visit(node.name, as_ptr=True)

        # 验证指针类型
        if not isinstance(base_ptr.type, ir.PointerType):
            raise TypeError("结构体成员访问需要指针类型")

        # 获取指针指向的实际类型
        pointee_type = base_ptr.type.pointee
        print(f"DEBUG: 基地址类型 {pointee_type}")  # 调试输出

        # 检查是否为已定义的结构体类型
        if not isinstance(pointee_type, ir.IdentifiedStructType):
            raise TypeError(f"非结构体类型 ({pointee_type}) 上的成员访问")

        # 获取结构体布局信息
        struct_info = self.struct_types.get(pointee_type.name)
        if not struct_info:
            raise RuntimeError(f"结构体 {pointee_type.name} 未定义")

        # 查找成员索引
        member_index = next(
            i
            for i, (name, *_) in enumerate(struct_info[1]["members"])
            if name == node.field.name
        )

        # 生成GEP指令
        indices = [self.get_const_int(0), self.get_const_int(member_index)]
        elem_ptr = self.builder.gep(base_ptr, indices, inbounds=True)

        return elem_ptr if as_ptr else self.builder.load(elem_ptr)

    def get_size(self, ir_type):
        """获取类型大小（支持结构体类型）"""
        if isinstance(ir_type, ir.IntType):
            return ir_type.width // 8  # 例如i32返回4
        elif isinstance(ir_type, ir.FloatType):
            return 4
        elif isinstance(ir_type, ir.PointerType):
            return 8  # 假设64位系统
        elif isinstance(ir_type, ir.ArrayType):
            return ir_type.count * self.get_size(ir_type.element)
        elif isinstance(ir_type, ir.IdentifiedStructType):
            if ir_type.name not in self.struct_types:
                raise RuntimeError(f"未知结构体类型: {ir_type.name}")
            return self.struct_types[ir_type.name][1]["size"]
        else:
            raise NotImplementedError(f"未支持的类型: {type(ir_type)}")

    def get_alignment(self, ir_type):
        """获取类型对齐值（支持结构体类型）"""
        if isinstance(ir_type, ir.IntType):
            return ir_type.width // 8
        elif isinstance(ir_type, ir.FloatType):
            return 4
        elif isinstance(ir_type, ir.PointerType):
            return 8
        elif isinstance(ir_type, ir.ArrayType):
            return self.get_alignment(ir_type.element)
        elif isinstance(ir_type, ir.IdentifiedStructType):
            if ir_type.name not in self.struct_types:
                raise RuntimeError(f"未知结构体类型: {ir_type.name}")
            return self.struct_types[ir_type.name][1]["align"]
        else:
            raise NotImplementedError(f"未支持的类型: {type(ir_type)}")

    def calc_padding(self, offset, align):
        """计算需要填充的字节数"""
        return (align - (offset % align)) % align

    # 常量表达式求值增强
    def eval_sizeof(self, expr):
        if isinstance(expr.expr, ast.Typename):
            target_type = self.get_type(expr.expr.type)
        else:
            target_type = self.get_type(expr.expr)
        return self.get_size(target_type)

    def eval_expr(self, expr, as_ptr=False):
        """表达式求值扩展"""
        if as_ptr:
            # 需要返回指针的特殊处理
            if isinstance(expr, ast.ID):
                return self.symbol_table[expr.name]
            elif isinstance(expr, ast.StructRef):
                return self.visit_StructRef(expr)
        return super().eval_expr(expr)


from ctypes import CFUNCTYPE, c_int
import llvmlite.binding as llvm

# 初始化LLVM环境
llvm.initialize()
llvm.initialize_native_target()
llvm.initialize_native_asmprinter()


def create_execution_engine():
    """创建JIT执行引擎"""
    target = llvm.Target.from_default_triple()
    target_machine = target.create_target_machine()
    backing_mod = llvm.parse_assembly("")
    engine = llvm.create_mcjit_compiler(backing_mod, target_machine)
    return engine


def compile_and_run(module):
    """编译并运行LLVM模块中的main函数"""
    # 1. 获取LLVM IR字符串
    llvm_ir = str(module)

    # 2. 创建执行引擎
    engine = create_execution_engine()

    # 3. 编译IR
    mod = llvm.parse_assembly(llvm_ir)
    mod.verify()  # 验证模块

    # 4. 添加到引擎
    engine.add_module(mod)
    engine.finalize_object()

    # 5. 获取main函数地址
    main_ptr = engine.get_function_address("main")

    # 6. 通过ctypes调用
    main_type = CFUNCTYPE(c_int)  # 假设main函数签名为int main()
    main_func = main_type(main_ptr)
    result = main_func()

    return result


import sys

if __name__ == "__main__":
    ast_root = parse_file(sys.argv[1])
    ast_root.show()
    generator = LLVMGenerator()
    module = generator.generate(ast_root)
    print(module)
    res = compile_and_run(module)
    print("执行结果：", res)
